package com.bw.controller.linkman;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.linkman.PiLinkman;
import com.bw.resp.ResponseResult;
import com.bw.service.customer.IPiCustomerService;
import com.bw.service.linkman.IPiLinkmanService;
import com.bw.utils.excel.ImportExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhouxin
 * @since 2020-06-16
 */
@CrossOrigin
@RestController
@RequestMapping("linkman")
public class PiLinkmanController {

    @Autowired
    private IPiLinkmanService piLinkmanService;

    @Autowired
    private IPiCustomerService customerService;

    private final Logger  logger = LoggerFactory.getLogger(PiLinkmanController.class);


    /*
    * 列表查询
    * */
    @PostMapping("list/{pagenum}/{pagesize}")
    public ResponseResult list(@RequestBody PiLinkman piLinkman,@PathVariable("pagenum") Integer currentPage,@PathVariable("pagesize") Integer pageSize){
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("用户列表查询");
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            PageHelper.startPage(currentPage,pageSize);
            if (piLinkman.getName()!=null){
               queryWrapper.like("name",piLinkman.getName());
            }
            List<PiLinkman> list = piLinkmanService.list(queryWrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setMessage("查询成功!");
            result.setResult(pageInfo);
        }catch (Exception e){
            logger.error("查询失败，{}",e.toString());
            result.setMessage("查询失败!"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping("addLinkMan")
    public ResponseResult addLinkMan(@RequestBody PiLinkman linkman){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            piLinkmanService.saveOrUpdate(linkman);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("保存失败!"+e.toString());
        }
        return result;
    }

    @PostMapping("LookDetail/{id}")
    public ResponseResult LookDetail(@PathVariable("id") String id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiLinkman piLinkman = piLinkmanService.getById(id);
            result.setResult(piLinkman);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败!"+e.toString());
        }
        return result;
    }

    @DeleteMapping("deleteLinkMan/{id}")
    public ResponseResult deleteLinkMan(@PathVariable("id") Long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiLinkman piLinkman = piLinkmanService.getById(id);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("删除失败!"+e.toString());
        }
        return result;
    }

    @PostMapping("importExcel")
    public ResponseResult importExcel(MultipartFile file){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());

            System.out.println(ext);

            InputStream inputStream = file.getInputStream();

            List<Map> maps = ImportExcel.readExcel(ext,inputStream);

            System.out.println(maps);

            String jsonString = JSON.toJSONString(maps);

            List<PiLinkman> piLinkmen = JSON.parseArray(jsonString, PiLinkman.class);

            piLinkmanService.saveBatch(piLinkmen);

        }catch (Exception e){
            e.toString();
            result.setMessage("失败");
            result.setSuccess(false);
        }
        return result;
    }

    @GetMapping("exportExcel")
    public void exportExcel(HttpServletResponse response){
        try {
            //从数据库获取数据
            List<PiLinkman> piLinkmen = piLinkmanService.list();
            //创建路径数据源路径
            ClassPathResource classPathResource = new ClassPathResource("xls/linkman.xls");
            //将文件添加到输入刘中
            InputStream inputStream = classPathResource.getInputStream();
            //利用工具类添加数据到
            ExcelUtils.addValue("list",piLinkmen);

            //第一个参数是模板流

            response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition","attachment;filename="+new String("客户数据".getBytes(),"iso-8859-1")+".xlsx");

            ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());
        }catch (Exception e){
            e.toString();
        }

    }

    @PostMapping("getCustomerList")
    public ResponseResult getCustomerList(){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            List<PiCustomer> customerList = customerService.list();
            result.setMessage("查询成功！");
            result.setResult(customerList);
        }catch (Exception e){
            result.setResult(false);
            result.setMessage("失败!");
        }
        return result;
    }


}
